# -*- python -*-
#
# Copyright (c) 2016 Stefan Seefeld
# All rights reserved.
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)

from faber import platform
from faber.feature import set
from faber.tools.compiler import runpath
from faber.tools.python import python, pythonpath
from faber.artefacts.object import object
from faber.artefacts.binary import binary
from faber.artefacts.python import extension
from faber.test import test, report, fail

src = module('..src')

python_libs=python.instance().libs
features |= runpath(src.bpl.path, base='')

def extension_test(name, exts=[], script=None, numpy=False,
                   features=features, condition=None):
    """Create a Python extension test `name`.
    Arguments:
      * name: the name of the test.
      * exts: extensions to be compiled, <name> if none are given.
      * script: the test script to execute, <name>.py if none is given.
      * numpy: if true, add boost_numpy to sources
      * features: pre-defined features
      * condition: any condition under which to run the test
    Return:
      * the test artefact"""

    features=features.copy()
    extensions = []
    libs = [src.bnl, src.bpl] if numpy else [src.bpl]
    for ext in exts or [name]:
        if type(ext) is str:  # build from a single source file
            ext_name = ext if ext != name else ext + '_ext'
            sources = [ext + '.cpp']
        else:  # build from a list of source files
            ext_name = ext[0] if ext[0] != name else ext[0] + '_ext'
            sources = [source + '.cpp' for source in ext]
        ext = extension(ext_name, sources + libs, features=features)
        features |= pythonpath(ext.path, base='')
        extensions.append(ext)
    if not script:
        script = name+'.py'
    return test(name, script, run=python.run, dependencies=extensions,
                features=features, condition=condition)

tests = []
for t in [('injected',),
          ('properties',),
          ('return_arg',),
          ('staticmethod',),
          ('boost_shared_ptr',),
          ('enable_shared_from_this',),
          ('andreas_beyer',),
          ('polymorphism',),
          ('polymorphism2',),
          ('wrapper_held_type',),
          ('minimal',),
          ('args',),
          ('raw_ctor',),
          ('exception_translator',),
          ('module_init_exception',),
          ('test_enum', ['enum_ext']),
          ('test_cltree', ['cltree']),
          ('newtest', ['m1', 'm2']),
          ('const_argument',),
          ('keywords_test', ['keywords']),
          ('test_pointer_adoption',),
          ('operators',),
          ('operators_wrapper',),
          ('callbacks',),
          ('defaults',),
          ('object',),
          ('class',),
          ('aligned_class',),
          ('list',),
          ('long',),
          ('dict',),
          ('tuple',),
          ('str',),
          ('slice',),
          ('virtual_functions',),
          ('back_reference',),
          ('implicit',),
          ('data_members',),
          ('ben_scott1',),
          ('bienstman1',),
          ('bienstman2',),
          ('bienstman3',),
          ('multi_arg_constructor',),
          ('iterator', ['iterator', 'input_iterator']),
          ('stl_iterator',),
          ('extract',),
          ('crossmod_opaque', ['crossmod_opaque_a', 'crossmod_opaque_b']),
          ('opaque',),
          ('voidptr',),
          ('pickle1',),
          ('pickle2',),
          ('pickle3',),
          ('pickle4',),
          ('nested',),
          ('docstring',),
          ('pytype_function',),
          ('vector_indexing_suite',),
          ('pointer_vector',),
          ('builtin_converters', [], 'test_builtin_converters.py'),
          ('map_indexing_suite',
           [['map_indexing_suite', 'int_map_indexing_suite', 'a_map_indexing_suite']])]:
    tests.append(extension_test(*t))

tests.append(extension_test('shared_ptr',
                            condition=set.define.contains('HAS_CXX11')))
tests.append(extension_test('polymorphism2_auto_ptr',
                            condition=set.define.contains('HAS_CXX11').not_()))
tests.append(extension_test('auto_ptr',
                            condition=set.define.contains('HAS_CXX11')))

import_ = binary('import_', ['import_.cpp', src.bpl], features=features|python_libs)
if platform.os == 'Windows':
    command = """set PATH=$(runpath);%PATH%
$(>[0]) $(>[1])"""
else:
    command = 'LD_LIBRARY_PATH=$(runpath) $(>[0]) $(>[1])'

tests.append(test('import', [import_, 'import_.py'],
                  run=action('run', command),
                  features=features))

tests.append(extension_test('calling_conventions',
                            condition=platform.os == 'Windows'))
tests.append(extension_test('calling_conventions_mf',
                            condition=platform.os == 'Windows'))

for t in ['destroy_test',
          'pointer_type_id_test',
          'bases',
          'pointee',
          'if_else',
          'pointee',
          'result',
          'upcast',
          'select_from_python_test']:
    tests.append(test(t, binary(t, [t + '.cpp', src.bpl], features=features), features=features, run=True))
for t in ['indirect_traits_test',
          'string_literal',
          'borrowed',
          'object_manager',
          'copy_ctor_mutates_rhs',
          'select_holder',
          'select_arg_to_python_test']:
    tests.append(test(t, object(t, [t + '.cpp'], features=features)))

for t in ['raw_pyobject_fail1',
          'raw_pyobject_fail2',
          'as_to_python_function',
          'object_fail1']:
    tests.append(test(t, object(t, [t + '.cpp'], features=features), expected=fail))

for t in ['numpy/dtype',
          'numpy/ufunc',
          'numpy/templates',
          'numpy/ndarray',
          'numpy/indexing',
          'numpy/shapes']:
    tests.append(extension_test(t, numpy=True,
                                condition=set.define.contains('HAS_NUMPY')))

default = report('report', tests, fail_on_failures=True)
